package com.yopuo.framework.web.service;

import com.yopuo.common.constant.Constants;
import com.yopuo.common.core.domain.entity.SysUser;
import com.yopuo.common.core.domain.model.LoginUser;
import com.yopuo.common.core.redis.RedisCache;
import com.yopuo.common.exception.CustomException;
import com.yopuo.common.exception.user.CaptchaException;
import com.yopuo.common.exception.user.CaptchaExpireException;
import com.yopuo.common.exception.user.UserPasswordNotMatchException;
import com.yopuo.common.utils.MessageUtils;
import com.yopuo.common.utils.StringUtils;
import com.yopuo.common.utils.sign.RsaUtils;
import com.yopuo.framework.manager.AsyncManager;
import com.yopuo.framework.manager.factory.AsyncFactory;
import com.yopuo.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * 登录校验方法
 * 
 * @author ruoyi
 */
@Component
public class SysLoginService
{
    @Resource
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private RedisCache redisCache;

    @Resource
    private SysUserMapper sysUserMapper;

    /** 是否允许账户多终端同时登录（true允许 false不允许） */
    @Value("${token.soloLogin}")
    private boolean soloLogin;
    /**
     * 登录验证
     * 
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid)
    {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
        // 用户验证
        Authentication authentication = null;
        try
        {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, RsaUtils.decryptByPrivateKey(password)));
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new CustomException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        if (!soloLogin)
        {
            // 如果用户不允许多终端同时登录，清除缓存信息
            String userIdKey = Constants.LOGIN_USERID_KEY + loginUser.getUser().getUserId();
            String userKey = redisCache.getCacheObject(userIdKey);
            if (StringUtils.isNotEmpty(userKey))
            {
                redisCache.deleteObject(userIdKey);
                redisCache.deleteObject(userKey);
            }
        }
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 登录验证(免验证)
     *
     * @param panUserId 云盘用户名Id
     * @return 结果
     */
    public String loginNoPasser(Long panUserId)
    {
        //根据云盘id查询用户
        SysUser user = new SysUser();
        user.setRemark(panUserId.toString());
        List<SysUser> users = sysUserMapper.selectUserList(user);
        if (CollectionUtils.isEmpty(users)){
            throw new RuntimeException("用户不存在");
        }
        SysUser sysUser = users.get(0);
        LoginUser loginUser = new LoginUser();
        loginUser.setUser(sysUser);
        loginUser.setExpireTime(30*60*1000L);
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setOs("windows");
        loginUser.setBrowser("google");
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(sysUser.getUserName(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        // 生成token
        return tokenService.createToken(loginUser);
    }
}
